// 获取应用实例
const app = getApp()

import { add, count } from "../../utils/db"
Page({
  data: {
    hedaer: '测试',
    error: ""
  },
  async formSubmit(e) {

    wx.showLoading({
      title: '正在提交',
    })
    //检测是否已经添加信息
    let openid = wx.getStorageSync("openid");
    let result = await count({ collection: "users", where: { _openid: openid } }).catch(err => {
      console.error(err)
    })

    if (result.total != 0) {
      wx.showToast({
        image: "/images/alert.png",
        title: "您已经抽过奖了~"
      })
      return;
    }

    //向users集合中添加用户信息
    let { realname, phone } = e.detail.value;
    let { avatarUrl } = wx.getStorageSync('userInfo');
    //检测手机号
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      this.setData({
        error: "手机号格式错误"
      })
      return;
    }

    result = await add({ collection: "users", data: { realname, phone, avatarUrl } }).catch(err => {
      console.error(err)
    })
    // console.log(result)
    //把手机号存储到本地缓存
    let userInfo = wx.getStorageSync('userInfo')
    userInfo.phone = phone
    userInfo.realname=realname;
    wx.setStorageSync('userInfo', userInfo)
    wx.hideLoading()
    wx.navigateTo({
      url: '../raffleticket/raffleticket'
    })
  }
})